<template>
  <!-- 商品详情顶部内容容器 -->
  <div class="detail-top-content">
    <!-- 骨架屏 - 当数据加载中显示 -->
    <template v-if="loading">
      <section class="go-flex left-image">
        <div class="thumbnail-nav skeleton">
          <a-space direction="vertical" size="small">
            <a-skeleton-image :active="true" size="small" shape="square" style="width: 90px; height: 120px;" v-for="i in 5" :key="i" />
          </a-space>
        </div>
        <div class="product-gallery">
          <a-skeleton-image :active="true" style="width: 100%; height: 627px;" />
        </div>
      </section>

      <section class="product-info skeleton-info">
        <a-skeleton :active="true" :paragraph="{ rows: 1 }" :title="{ width: '40%' }" />
        <a-skeleton :active="true" :paragraph="{ rows: 0 }" :title="{ width: '70%' }" />
        <a-skeleton :active="true" :paragraph="{ rows: 0 }" :title="{ width: '60%' }" />

        <div class="skeleton-options" style="margin-top: 24px; padding-top: 15px; border-top: 1px solid #e5e5e5;">
          <a-skeleton :active="true" :paragraph="{ rows: 0 }" :title="{ width: '30%' }" />
          <a-space style="margin: 12px 0 20px;">
            <a-skeleton-button :active="true" size="small" shape="circle" v-for="i in 4" :key="i" style="width: 30px; height: 30px;" />
          </a-space>
          <a-skeleton :active="true" :paragraph="{ rows: 0 }" :title="{ width: '30%' }" />
          <a-skeleton-button :active="true" style="width: 100%; margin-top: 16px;" />
        </div>

        <div style="margin-top: 24px;">
          <a-skeleton-button :active="true" block style="height: 40px;" />
        </div>

        <div style="margin-top: 30px;">
          <a-skeleton :active="true" :paragraph="{ rows: 3 }" :title="false" />
        </div>
      </section>
    </template>

    <!-- 正常内容 - 当数据加载完成显示 -->
    <template v-else>
      <!-- 左侧图片区域 -->
      <section class="go-flex left-image">
        <!-- 缩略图导航区域 -->
        <div class="thumbnail-nav">
          <!-- 向上滚动按钮 -->
          <button class="nav-arrow up" @click="prevThumbnail" :disabled="currentImageIndex === 0">
            <span class="arrow">
              <UpOutlined />
            </span>
          </button>
          <!-- 缩略图列表 -->
          <div class="thumbnail-list">
            <div v-for="(image, index) in productData.detail_images" :key="index" class="thumbnail"
              :class="{ active: currentImageIndex === index }" @click="selectImage(index)">
              <img :src="image" :alt="`${productData.name} - view ${index + 1}`" />
            </div>
          </div>
          <!-- 向下滚动按钮 -->
          <button class="nav-arrow down" @click="nextThumbnail"
            :disabled="currentImageIndex === productData.detail_images.length - 1">
            <span class="arrow">
              <DownOutlined />
            </span>
          </button>
        </div>

        <!-- 商品主图展示区域 -->
        <div class="product-gallery">
          <!-- 上一张图片按钮 -->
          <button class="gallery-nav prev" @click="prevImage" v-if="currentImageIndex > 0">
            <span class="arrow">&#x2039;</span>
          </button>
          <!-- 主图显示区域 -->
          <div class="main-image">
            <img :src="currentImage" :alt="productData.name" />
          </div>
          <!-- 下一张图片按钮 -->
          <button class="gallery-nav next" @click="nextImage"
            v-if="productData.detail_images && currentImageIndex < productData.detail_images.length - 1">
            <span class="arrow">&#x203A;</span>
          </button>
        </div>
      </section>

      <!-- 商品信息区域 -->
      <section class="product-info">
        <!-- 商品标题和价格 -->
        <div class="product-header">
          <!-- <h1 class="brand-name">Duonin</h1> -->
          <h2 class="product-name">{{ productData.name }}</h2>
          <div class="product-price go-flex-sc">
            <div class="price-container">
              <span class="current-price" :class="{ 'discount-price': hasDiscount }">
                {{ useCurrency.currentCurrency.unit }} {{ proxy.$ConvertPrice(currentPrice) }}
              </span>
              <span v-if="hasDiscount" class="original-price">
                {{ useCurrency.currentCurrency.unit }} {{ proxy.$ConvertPrice(currentOriginalPrice) }}
              </span>
              <span v-if="hasDiscount" class="discount-tag">
                -{{ 100 - discountPercent }}%
              </span>
            </div>
            <div class="product-price-num">
              <img :src="SVG_ICONS.visit" /><span v-show="visitCount">{{ visitCount }}</span>
            </div>
          </div>
        </div>

        <!-- 商品选项区域 -->
        <div class="product-options">
          <!-- 颜色选择 -->
          <div class="option-group" v-if="availableColors.length > 0">
            <div class="option-label">
              COLOUR:
            </div>
            <div v-if="selectedColorName" class="selected-color-display">
              <a-input class="color-name-input" disabled :value="selectedColorName">
                <template #prefix>
                  <span class="color-indicator" :style="{ backgroundImage: colorActive ? `url(${colorActive})` : 'none' }"></span>
                </template>
              </a-input>
            </div>
            <div class="color-options">
              <a-radio-group v-model:value="colorActive" class="color-radio-group" @change="handleColorChange">
                <a-radio v-for="(color, index) in availableColors" :key="index" :value="color" class="color-radio">
                  <div class="color-swatch-container">
                    <img class="color-swatch-img" :src="color" :class="{ active: colorActive === color }" />
                  </div>
                </a-radio>
              </a-radio-group>
            </div>
          </div>

          <!-- 尺码选择 -->
          <div class="option-group" v-if="availableSizes.length > 0">
            <div class="option-label size-header">
              <span>SIZE:</span>
              <a class="size-guide" @click="showSizeGuide">SIZE GUIDE</a>
            </div>
            <div class="size-selector">
              <!-- 使用 a-select 替换自定义尺码选择 -->
              <a-select
                v-model:value="sizeActive"
                placeholder="CHOOSE SIZE"
                :options="availableSizes.map(size => ({ value: size, label: size }))"
                class="size-select"
                @change="selectSize"
                :status="sizeError ? 'error' : ''"
              />
              <div v-if="sizeError" class="size-error-tip">
                <a-alert type="error" message="Please select a size" banner />
              </div>
            </div>
          </div>
        </div>

        <!-- 添加到购物袋和收藏按钮 -->
        <div class="product-actions">
          <div class="action-buttons">
            <!-- 收藏按钮 -->
            <a-tooltip :title="productData.favorite ? 'Cancel Favorites' : 'Add to favorites'">
              <a-button
                shape="circle"
                class="wishlist-button"
                @click="collectFn()"
              >
                <template #icon>
                  <img
                    :src="productData.favorite ? SVG_ICONS.favouriteActive : SVG_ICONS.favouriteDefault"
                    alt="Wishlist"
                  />
                </template>
              </a-button>
            </a-tooltip>
            <!-- 添加到购物袋按钮 -->
            <a-button type="primary" class="add-to-bag" @click="buyFn" block>
              ADD TO BAG
            </a-button>
          </div>
        </div>

        <!-- 配送信息 -->
        <!-- TODO 还未对接 -->
        <div class="delivery-info">
          <div class="delivery-icon">
            <img
              src="https://www.reiss.com/static-content/ux-fabric/iconography-graphics/feature/reiss/deliveryreturns-xl-default.svg"
              alt="Delivery" />
          </div>
          <div class="delivery-text">
            <p>FREE NEXT DAY DELIVERY AND RETURNS TO OUR STORES ANDOVER 600 OTHER LOCATIONS. FOR OTHER DELIVERY ANDRETURNS
              OPTIONS AND CHARGES <a href="#" @click="toTerms" class="terms-link">CLICK HERE</a></p>
          </div>
        </div>

        <!-- 商品描述 -->
        <div class="product-description">
          <p :class="{ 'truncated': !showFullDescription }">{{ productData.description }}</p>
          <button v-if="isDescriptionLong" class="read-more" @click="toggleDescription">
            {{ showFullDescription ? 'SHOW LESS' : 'READ MORE' }}
          </button>
        </div>

        <!-- 商品编号 -->
        <div class="product-code">
          <span>PRODUCT CODE:</span>Lannuan-{{ productData.id }}
        </div>

        <!-- 商品详情和保养信息 -->
        <div class="product-details" v-for="(item, index) in productData.goods_service" :key="index">
          <button class="details-button" @click="toggleCareInfo(index)">
            <span>{{ item.name }}</span>
            <span class="dropdown-arrow" :class="{ 'arrow-up': showCareInfo[index] }">
              <DownOutlined :style="{ fontSize: '10px' }" />
            </span>
          </button>
          <div class="care-info" v-show="showCareInfo[index]">
            <p>{{ item.content }}</p>
          </div>
        </div>
      </section>
    </template>
  </div>
  <a-drawer
    title="Size Guide"
    :placement="placement"
    :closable="true"
    :visible="sizeVisible"
    :width="480"
    @close="onClose"
  >
    <template v-if="loading">
      <a-skeleton :active="true" :paragraph="{ rows: 10 }" />
    </template>
    <template v-else>
      <size-table :sizeData="productData"></size-table>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, nextTick, getCurrentInstance } from 'vue';
import { UpOutlined, DownOutlined } from '@ant-design/icons-vue';
import SVG_ICONS from "@/assets/SVG_ICONS";
import { addVisit, addFavorite, getDetail, addCarts } from "@/api/goods";
import { deleteCollect } from "@/api/user";
import { useCurrencyStore } from '@/store'
import sizeTable from '../views/GoodDetails/components/sizeTable.vue';
import { message, Skeleton, SkeletonButton, SkeletonImage, Space, Tag, Input, Select, Button, Radio } from 'ant-design-vue';
import {
  addToBrowsingHistory,
  isInFavorites,
  CartAdapter,
  addToFavorites as addToFavoritesLocal,
  removeFromFavorites as removeFromFavoritesLocal
} from '@/utils/cache';
import emitter from '@/utils/eventBus';
import {Local,Session} from "@/utils/storage";
import { useRouter } from 'vue-router';
import {getFavoriteList} from "@/api/details.ts";
const router = useRouter();
const isLogin = !!Local.get('user_token');

// 控制加载状态
const loading = ref(true);

const sizeVisible = ref(false)
const onClose = ()=>{
  sizeVisible.value = false
}
// Add placement variable with default value 'right'
const placement = ref('right')
interface GoodsService {
  name: string;
  content: string;
}

interface SpecValue {
  name: string;
  value: string;
}

interface SkuItem {
  id: number;
  goods_id: number;
  spec_parsed: SpecValue[];
  spec: SpecValue[];
  image: string;
  price: string;
  origin_price: string;
  stock: number;
  goods_name: string;
  color_name?: string;
}

interface ProductData {
  id: number;
  name: string;
  price: number;
  description: string;
  sku_list: SkuItem[];
  detail_images: string[];
  code?: string;
  care_instructions?: string;
  favorite?: boolean;
  goods_service?: GoodsService[];
  min_price?: string;
  min_origin_price?: string;
  discount_enabled?: number;
  discount?: number;
}

const useCurrency = useCurrencyStore()
const { proxy } = getCurrentInstance()

const props = defineProps<{
  goodId: string;
}>();

const detailData = ref<ProductData>({
  id: 0,
  name: '',
  price: 0,
  description: '',
  spec_list: [],
  detail_images: [],
  favorite: false,
  goods_service: [
    {
      name: '',
      content: ''
    }
  ]
})

//获取商品详情
const getDetailData = () => {
  loading.value = true;
  getDetail(props.goodId).then(res => {
    if (res.code === 200) {
      detailData.value = res.result.goods_detail;
      // 检查商品是否已被收藏
      if (!detailData.value.favorite) {
        detailData.value.favorite = isInFavorites(detailData.value.id);
      }
      // 添加到浏览历史
      addToBrowsingHistory(res.result.goods_detail);
    }
    loading.value = false;
  }).catch(error => {
    console.error('Failed to fetch product details:', error);
    loading.value = false;
  });
}

onMounted(() => {
  getDetailData();
});


/**
 * 默认商品数据
 * 用于初始化商品数据状态
 */
const defaultProduct: ProductData = {
  id: 0,
  name: '',
  price: 0,
  description: '',
  sku_list: [],
  detail_images: [],
};

// 状态管理
const productData = ref<ProductData>({ ...defaultProduct });
const currentImageIndex = ref(0);
const colorActive = ref('');
const sizeActive = ref('');
const selectedSkuId = ref<number | null>(null);
const selectedColorName = ref('');
const currentPrice = ref(''); // 当前选中SKU的价格
const currentOriginalPrice = ref(''); // 当前选中SKU的原价
const hasDiscount = ref(false); // 是否有折扣
const discountPercent = ref(0); // 折扣百分比

/**
 * 是否显示保养信息
 */
const showCareInfo = ref<boolean[]>([]);

/**
 * 是否显示完整描述
 */
const showFullDescription = ref(false);

/**
 * 是否显示尺码下拉菜单
 */
const showSizeDropdown = ref(false);

/**
 * 检查描述是否超过3行
 */
const isDescriptionLong = ref(false);

// 添加尺寸错误状态
const sizeError = ref(false);

const emit = defineEmits<{
  (e: 'buy', data: {
    skuId: number;
    selectedSize: string;
    selectedColor: string;
    price: string;
    image: string;
    goods_name: string;
  }): void;
}>();

// 计算属性
const currentImage = computed(() => {
  return productData.value.detail_images[currentImageIndex.value];
});

const availableSizes = computed(() => {
  if (!productData.value?.sku_list) return [];

  // 获取所有可用的尺码
  const sizes = new Set<string>();
  productData.value.sku_list.forEach(sku => {
    const sizeSpec = sku?.spec_parsed?.find(spec => spec?.name === 'Size' || spec?.name === 'size');
    if (sizeSpec?.value) {
      sizes.add(sizeSpec.value);
    }
  });
  return Array.from(sizes);
});

const availableColors = computed(() => {
  if (!productData.value?.sku_list) return [];

  // 获取所有可用的颜色
  const colors = new Set<string>();
  productData.value.sku_list.forEach(sku => {
    const colorSpec = sku?.spec_parsed?.find(spec => spec?.name === 'Color' || spec?.name === 'color');
    if (colorSpec?.value) {
      colors.add(colorSpec.value);
    }
  });
  return Array.from(colors);
});

// 提取得到颜色对象，包含颜色值和颜色名称
interface ColorInfo {
  value: string;
  colorName: string;
}

// 颜色名称映射
const colorNameMap = computed(() => {
  if (!productData.value?.sku_list) return new Map();

  const map = new Map<string, string>();
  productData.value.sku_list.forEach(sku => {
    const colorSpec = sku?.spec_parsed?.find(spec => spec?.name === 'Color' || spec?.name === 'color');
    if (colorSpec?.value && sku.color_name) {
      map.set(colorSpec.value, sku.color_name);
    }
  });
  return map;
});

// 更新折扣信息
const updateDiscountInfo = () => {
  if (!productData.value) return;

  // 检查商品是否启用折扣
  hasDiscount.value = productData.value.discount_enabled === 1;

  if (hasDiscount.value) {
    // 设置折扣百分比 - API返回的discount应该是折扣比例（如70表示7折，即70%的原价）
    discountPercent.value = productData.value.discount || 0;
  }
};

watch(() => detailData.value, (newVal) => {
  if (!newVal) return;

  productData.value = { ...newVal };

  // 处理规格数据
  if (productData.value?.sku_list?.length > 0) {
    // 获取第一个SKU的颜色和尺码作为默认值
    const firstSku = productData.value.sku_list[0];
    if (firstSku?.spec_parsed) {
      const colorSpec = firstSku.spec_parsed.find(spec => spec?.name === 'Color' || spec?.name === 'color');
      const sizeSpec = firstSku.spec_parsed.find(spec => spec?.name === 'Size' ||  spec?.name === 'size');

      if (colorSpec?.value) {
        colorActive.value = colorSpec.value;
        selectedColorName.value = firstSku.color_name || '';
      }
      if (sizeSpec?.value) {
        sizeActive.value = sizeSpec.value;
      }
      selectedSkuId.value = firstSku.id;
      // 设置初始价格
      currentPrice.value = firstSku.price || productData.value.min_price || '';
      // 设置初始原价
      currentOriginalPrice.value = firstSku.origin_price || productData.value.min_origin_price || '';
      // 更新折扣信息
      updateDiscountInfo();
    }
  } else {
    // 如果没有SKU列表，使用最低价格
    currentPrice.value = productData.value.min_price || '';
    currentOriginalPrice.value = productData.value.min_origin_price || '';
    // 更新折扣信息
    updateDiscountInfo();
  }
}, { immediate: true });

onMounted(() => {
  checkDescriptionLength();
  // 刷新最近浏览
  refreshVisit()

})

const visitCount = ref(null)
// 刷新最近浏览
const refreshVisit = () => {
  addVisit({ id: props.goodId }).then((res: any) => {
    if (res.code == 200) {
      visitCount.value = res.result.visit
    }
  })

}

const toTerms = () => {
  // 重新打开一个页签到terms页面
  window.open('/terms', '_blank');
};

// 方法定义
const prevImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  }
};

const nextImage = () => {
  if (productData.value.detail_images && currentImageIndex.value < productData.value.detail_images.length - 1) {
    currentImageIndex.value++;
  }
};

const selectImage = (index: number) => {
  currentImageIndex.value = index;
};

const colorClick = (color: string) => {
  if (!color) return;
  colorActive.value = color;

  // 查找具有该颜色的 sku 并获取 color_name
  const skuWithColor = productData.value.sku_list?.find(sku => {
    const colorSpec = sku?.spec_parsed?.find(spec =>
      (spec?.name === 'Color' || spec?.name === 'color') && spec?.value === color
    );
    return !!colorSpec;
  });

  selectedColorName.value = skuWithColor?.color_name || '';

  // 获取当前颜色可用的尺寸列表
  const availableSizesForColor = productData.value.sku_list
    ?.filter(sku => {
      const colorSpec = sku?.spec_parsed?.find(spec =>
        (spec?.name === 'Color' || spec?.name === 'color') && spec?.value === color
      );
      return !!colorSpec;
    })
    .map(sku => {
      const sizeSpec = sku?.spec_parsed?.find(spec =>
        (spec?.name === 'Size' || spec?.name === 'size')
      );
      return sizeSpec?.value || '';
    })
    .filter(size => size !== '');

  // 如果有可用尺寸，选择第一个作为默认值
  if (availableSizesForColor && availableSizesForColor.length > 0) {
    sizeActive.value = availableSizesForColor[0];
    // 重置尺寸错误状态
    sizeError.value = false;
    // 更新选中的SKU
    updateSelectedSku();
  } else {
    // 如果没有可用尺寸，则清空尺寸选择
    sizeActive.value = '';
  }
};

const selectSize = (size: string) => {
  if (!size) return;
  sizeActive.value = size;
  updateSelectedSku();
};

// 工具函数：从规格字符串中提取尺码
const extractSize = (specString: string) => {
  const parts = specString.split(';');
  for (const part of parts) {
    if (part.startsWith('Size:')) {
      return part.replace('Size:', '');
    }
  }
  return '';
};

// 工具函数：从规格字符串中提取颜色URL
const extractColor = (specString: string) => {
  const parts = specString.split(';');
  for (const part of parts) {
    if (part.startsWith('Color:')) {
      return part.replace('Color:', '');
    }
  }
  return '';
};

// 更新选中的SKU
const updateSelectedSku = () => {
  if (!colorActive.value || !sizeActive.value || !productData.value?.sku_list) return;

  const selectedSku = productData.value.sku_list.find(sku => {
    if (!sku?.spec_parsed) return false;

    const colorMatch = sku.spec_parsed.some(spec =>
      (spec?.name === 'Color' || spec?.name === 'color') && spec?.value === colorActive.value
    );
    const sizeMatch = sku.spec_parsed.some(spec =>
      (spec?.name === 'Size' || spec?.name === 'size') && spec?.value === sizeActive.value
    );
    return colorMatch && sizeMatch;
  });

  if (selectedSku) {
    selectedSkuId.value = selectedSku.id;
    // 更新当前价格
    currentPrice.value = selectedSku.price;
    // 更新原价
    currentOriginalPrice.value = selectedSku.origin_price;
    // 检查并更新折扣信息
    updateDiscountInfo();
  }
};

const buyFn = async () => {
  // 重置错误状态
  sizeError.value = false;
//检查登录状态
  if(!isLogin){
    message.warn('Please login');
    // 跳转登录页面
    setTimeout(() => {
      router.push('/login');
    }, 1000);
    return;
  }
  if (!sizeActive.value && availableSizes.value.length > 0) {
    message.warn('Please select a size');
    sizeError.value = true;
    return;
  }
  if (!colorActive.value && availableColors.value.length > 0) {
    message.warn('Please select a color');
    return;
  }
  if (!selectedSkuId.value) {
    message.warn('Please select a valid combination');
    return;
  }

  // 找到选中的SKU完整信息
  const selectedSku = productData.value.sku_list?.find(sku => sku.id === selectedSkuId.value);
  if (!selectedSku) {
    alert('Selected SKU not found');
    return;
  }

  try {
    const res = await addCarts({
      sku_id: selectedSku.id,
      num: 1,
    });

    if (res.code === 200) {
      message.success('Add to cart success');

      // 获取现有购物车缓存
      const cartItems = CartAdapter.getCartItems() || [];

      // 构建购物车项目数据结构
      const cartItem = {
        id: selectedSku.id,  // 使用SKU ID作为购物车项目ID
        name: selectedSku.goods_name || productData.value.name,
        specs: `${colorActive.value}，${sizeActive.value}`,  // 使用颜色和尺寸构建规格文本
        price: parseFloat(selectedSku.price),
        quantity: 1,  // 每次添加1个
        stock: selectedSku.stock || 99,
        selected: true,  // 默认选中
        image: selectedSku.image || productData.value.detail_images[0],
        goods_id: productData.value.id,
        sku_id: selectedSku.id
      };

      // 检查商品是否已存在于购物车中
      const existingItemIndex = cartItems.findIndex(item =>
        item.sku_id === selectedSku.id
      );

      if (existingItemIndex > -1) {
        // 如果已存在，增加数量
        cartItems[existingItemIndex].quantity += 1;
      } else {
        // 如果不存在，添加新项
        cartItems.push(cartItem);
      }

      // 更新购物车缓存
      CartAdapter.saveCartItems(cartItems);

      emitter.emit('getCartList');

    } else {
      message.error('Add to cart failed');
    }

    emit('buy', {
      skuId: selectedSku.id,
      selectedSize: sizeActive.value,
      selectedColor: colorActive.value,
      price: selectedSku.price,
      image: selectedSku.image,
      goods_name: selectedSku.goods_name
    });

  } catch (error) {
    console.error('Failed to add to cart:', error);
  }
};

const collectFn = async () => {
  if (!isLogin) {
    message.warning('Please login first');
    setTimeout(() => {
      router.push('/login');
    }, 1000);
    return;
  }

  try {
    // 检查当前收藏状态
    const isFavorited = productData.value.favorite;

    // 执行收藏或取消收藏操作
    const res = isFavorited
      ? await deleteCollect({ goods_id: productData.value.id })
      : await addFavorite(String(productData.value.id));

    if (res.code === 200) {
      // 更新UI状态
      productData.value.favorite = !isFavorited;

      // 同时更新本地缓存并显示提示信息
      if (isFavorited) {
        // removeFromFavoritesLocal(productData.value.id);
        favoriteList()
        // message.success('已取消收藏');
      } else {
        // 构建一个包含必要信息的对象传递给缓存函数
        const favoriteItem = {
          id: productData.value.id,
          goods_id: productData.value.id,
          name: productData.value.name,
          images: productData.value.detail_images || [],
          min_price: productData.value.min_price || productData.value.price
        };
        // addToFavoritesLocal(favoriteItem);
        favoriteList()
        // message.success('已添加到收藏夹');
      }
    }
  } catch (error) {
    console.error('Failed to update favorite status:', error);
    // message.error('操作失败，请稍后重试');
  }
};
//收藏列表
const favoriteList = async () => {
  const favoriteRes = await getFavoriteList()
  if(favoriteRes.code === 200){
    emitter.emit('getFavoriteApi');
    Session.set('collectList', favoriteRes.result)
  }
}
const prevThumbnail = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  }
};

const nextThumbnail = () => {
  if (productData.value.detail_images && currentImageIndex.value < productData.value.detail_images.length - 1) {
    currentImageIndex.value++;
  }
};

const checkDescriptionLength = () => {
  nextTick(() => {
    const descriptionElement = document.querySelector('.product-description p');
    if (descriptionElement) {
      const lineHeight = parseInt(getComputedStyle(descriptionElement).lineHeight);
      const height = descriptionElement.clientHeight;
      isDescriptionLong.value = height > lineHeight * 3;
    }
  });
};

watch(() => productData.value.description, () => {
  nextTick(() => {
    checkDescriptionLength();
  });
});


const toggleCareInfo = (index: number) => {
  if (!showCareInfo.value[index]) {
    showCareInfo.value[index] = true;
  } else {
    showCareInfo.value[index] = false;
  }
};

const toggleDescription = () => {
  showFullDescription.value = !showFullDescription.value;
};

const showSizeGuide = () => {
  // 实现尺码指南弹窗
  sizeVisible.value = true
};

const toggleSizeDropdown = () => {
  showSizeDropdown.value = !showSizeDropdown.value;
};

// 处理颜色变化
const handleColorChange = (e: any) => {
  const color = e.target.value;
  colorClick(color);
};
</script>

<style lang="scss" scoped>
/* 商品详情顶部内容容器样式 */
.detail-top-content {
  display: grid;
  grid-template-columns: 1fr;
  margin: 0 auto;
  font-family: Arial, sans-serif;

  /* 响应式布局：在中等屏幕及以上使用两列布局 */
  @media (min-width: 768px) {
    grid-template-columns: 1fr 1fr;
  }
}

/* 左侧图片区域样式 */
.left-image {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: top;
  gap: 25px;
}

/* 商品图片展示区域样式 */
.product-gallery {
  position: relative;
  width: 100%;
  max-width: 470px;
  margin: 0;

  :deep(.ant-skeleton.ant-skeleton-element .ant-skeleton-image) {
    width: 100%;
    height: 627px;
  }

  /* 主图样式 */
  .main-image {
    width: 100%;
    max-width: 470px;
    max-height: 627px;
    height: auto;
    aspect-ratio: 3 / 4;
    overflow: hidden;
    margin-bottom: 10px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  /* 图片导航按钮样式 */
  .gallery-nav {
    position: absolute;
    top: 46%;
    transform: translateY(-50%);
    background: none;
    border: none;
    font-size: 24px;
    color: #000;
    cursor: pointer;
    padding: 10px;
    z-index: 2;

    &.prev {
      left: 10px;
    }

    &.next {
      right: 10px;
    }
  }
}

/* 缩略图导航样式 */
.thumbnail-nav {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 0;
  width: 90px;
  height: 627px;
  position: relative;

  /* 导航箭头按钮样式 */
  .nav-arrow {
    width: 100%;
    height: 30px;
    background: none;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    color: #000;
    font-size: 12px;

    &:disabled {
      opacity: 0.3;
      cursor: not-allowed;
    }

    &.up {
      margin-bottom: 5px;
    }

    &.down {
      margin-top: 5px;
    }
  }

  /* 缩略图列表样式 */
  .thumbnail-list {
    flex: 1;
    display: flex;
    overflow-y: auto;
    flex-direction: column;
    scrollbar-width: none;
    align-items: center;
    justify-content: space-between;

    /* 隐藏滚动条 */
    &::-webkit-scrollbar {
      display: none;
    }
  }

  /* 单个缩略图样式 */
  .thumbnail {
    width: 90px;
    height: 120px;
    cursor: pointer;
    opacity: 0.6;
    transition: opacity 0.3s;
    margin-bottom: 8px;

    /* 激活状态样式 */
    &.active {
      opacity: 1;
      border-bottom: 2px solid #000;
    }

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  /* 响应式布局：在小屏幕上隐藏缩略图导航 */
  @media (max-width: 1020px) {
    display: none;
  }
}

/* 商品信息区域样式 */
.product-info {
  width: 100%;
  padding: 0;
  max-width: 470px;
  margin: 0 auto;

  /* 商品标题和价格样式 */
  .product-header {
    margin-bottom: 16px;

    .brand-name {
      font-size: 14px;
      font-weight: bold;
      margin: 0;
      letter-spacing: 0.5px;
    }

    .product-name {
      font-size: 14px;
      font-weight: bold;
      margin: 0 0 5px;
      letter-spacing: 0.5px;
    }

    .product-price {
      font-size: 14px;
      font-weight: bold;

      .price-container {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .current-price {
          font-size: 16px;
          margin-right: 8px;

          &.discount-price {
            color: #f00; /* 折扣价格显示为红色 */
          }
        }

        .original-price {
          font-size: 14px;
          color: #999;
          text-decoration: line-through;
          margin-right: 8px;
        }

        .discount-tag {
          font-size: 12px;
          background-color: #f00;
          color: white;
          padding: 2px 6px;
          border-radius: 2px;
        }
      }
    }

    .product-price-num {
      font-size: 12px;

      img {
        width: 25px;
        height: 25px;
      }

      span {
        position: relative;
        bottom: -2px;
      }
    }
  }

  /* 商品选项样式 */
  .product-options {
    border-top: 1px solid #e5e5e5;

    /* 选项组样式 */
    .option-group {
      .option-label {
        font-size: 12px;
        padding-top: 16px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .selected-color-display {
        margin-bottom: 12px;

        .color-name-input {
          width: 100%;
          font-size: 13px;
          font-weight: 500;

          &:deep(.ant-input) {
            background-color: #e8e8e8;
            color: #000000;
            height: 32px;
            border-color: #b8b8b8;
            border-width: 1px;
            border-radius: 3px;
            letter-spacing: 0.2px;
            font-size: 13px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
            padding-left: 8px;
            padding-right: 8px;
          }

          &:deep(.ant-input-disabled) {
            color: #000000;
            cursor: default;
            background-color: #e8e8e8;
            border-color: #b8b8b8;
          }

          &:deep(.ant-input-prefix) {
            margin-right: 8px;
          }

          .color-indicator {
            display: inline-block;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            margin-right: 4px;
            background-size: cover;
            border: 1px solid #b8b8b8;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
            vertical-align: middle;
          }
        }
      }

      .color-tag-wrapper {
        display: none;
      }

      .size-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 10px;
        font-weight: bold;

        .size-guide {
          font-size: 12px;
          text-decoration: underline;
          cursor: pointer;
          font-weight: bold;
          color: #000;
          margin-top: 0;
          padding: 0;
          background-color: transparent;
          border-radius: 0;
          border-left: 0;
        }

        span {
          font-weight: bold;
        }
      }
    }

    /* 颜色选项样式 */
    .color-options {
      margin-bottom: 15px;

      .color-radio-group {
        display: flex;
        flex-wrap: wrap;

        .color-radio {
          margin-right: 8px;
          margin-bottom: 8px;

          &:deep(.ant-radio) {
            display: none;
          }

          .color-swatch-container {
            padding: 2px;
            cursor: pointer;

            .color-swatch-img {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              border: 1px solid transparent;

              &.active {
                border: 1px solid #000;
              }
            }
          }
        }
      }
    }

    /* 尺码选择器样式 */
    .size-selector {
      position: relative;
      width: 100%;


      .size-select {
        width: 100%;

        &:deep(.ant-select-selector) {
          height: 32px;
          padding: 0 15px;
          display: flex;
          align-items: center;
          border-color: rgba(0, 0, 0, 0.87);
          border-radius: 0;
        }

        &:deep(.ant-select-selection-placeholder),
        &:deep(.ant-select-selection-item) {
          font-size: 12px;
          line-height: 32px;
        }

        &:deep(.ant-select-arrow) {
          color: rgba(0, 0, 0, 0.87);
        }
      }

      .size-error-tip {
        margin-top: 8px;

        &:deep(.ant-alert-error) {
          border: none;
          background-color: transparent;
          padding: 0;
        }

        &:deep(.ant-alert-message) {
          color: #ff4d4f;
          font-size: 12px;
        }
      }
    }
  }

  /* 商品操作按钮样式 */
  .product-actions {
    margin-bottom: 30px;
    margin-top: 37px;
    .action-buttons {
      display: flex;
      gap: 10px;
      width: 100%;

      /* 收藏按钮样式 */
      .wishlist-button {
        width: 38px;
        height: 38px;
        border: 1px solid #e0e0e0;
        display: flex;
        align-items: center;
        justify-content: center;

        &:deep(.ant-btn-icon) {
          display: flex;
          align-items: center;
          justify-content: center;
        }

        img {
          width: 20px;
          height: 20px;
        }
      }

      /* 添加到购物袋按钮样式 */
      .add-to-bag {
        flex: 1;
        background: #000;
        color: white;
        border: none;
        height: 36px;
        line-height: 36px;
        border-radius: 0;
        font-weight: bold;
        letter-spacing: 0.5px;

        &:hover {
          background: #333;
        }

        &:deep(.ant-btn-primary:not(:disabled)) {
          background-color: #000;
        }
      }
    }
  }

  /* 配送信息样式 */
  .delivery-info {
    border-top: 1px solid #e0e0e0;
    padding: 20px 0;
    font-size: 12px;
    line-height: 1.6;
    display: flex;

    .delivery-icon {
      margin-right: 15px;
      display: flex;
      align-items: center;
    }

    p {
      margin: 0px;
    }

    .terms-link {
      color: #000;
      text-decoration: underline;
    }
  }

  /* 商品描述样式 */
  .product-description {
    margin-bottom: 20px;
    font-size: 12px;
    line-height: 1.6;

    p {
      margin: 0;
      transition: max-height 0.3s ease;

      &.truncated {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .read-more {
      background: none;
      border: none;
      color: #000;
      text-decoration: underline;
      padding: 0;
      font-size: 12px;
      cursor: pointer;
      width: 100%;
      font-weight: bold;
      text-align: right;
      margin-top: 8px;
    }
  }

  /* 商品编号样式 */
  .product-code {
    font-size: 12px;
    color: #333;
    padding-bottom: 5px;
    border-bottom: 1px solid #e0e0e0;

    span {
      color: #000;
      font-weight: bold;
      margin-right: 6px;
    }
  }

  /* 商品详情和保养信息样式 */
  .product-details {
    border-bottom: 1px solid #e0e0e0;

    .details-button {
      width: 100%;
      padding: 12px 0 4px 0;
      background: none;
      border: 0;
      font-size: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;

      span {
        border: none;
        color: #000;
        font-weight: bold;
      }

      .dropdown-arrow {
        font-size: 10px;
        transition: transform 0.3s;

        /* 箭头向上旋转 */
        &.arrow-up {
          transform: rotate(180deg);
        }
      }
    }
  }
}

/* 响应式布局：小屏幕样式 */
@media (max-width: 767px) {
  .product-detail-container {
    gap: 20px;
    padding: 10px;
  }

  .product-info {
    padding: 0;
  }
}

/* 可能需要的骨架屏辅助样式 */
.skeleton-info {
  width: 100%;
  padding: 0;
  max-width: 470px;
  margin: 0 auto;
}
</style>
